package com.slliver.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.slliver.pojo.Product;
import com.slliver.service.ProductService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {

    private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }


    // 如果当前方法调用失败，调用备选方法
    @HystrixCommand(fallbackMethod = "hystrixGet")
    @GetMapping("/product/get/{id}")
    public Product get(@PathVariable("id") Long id) {
        Product product = this.productService.getProductById(id);
        if (product == null) {
            throw new RuntimeException("id ==>> " + id + ", 不存在，或者信息无法找到.");
        }
        return this.productService.getProductById(id);
    }

    // 如果id不存在，使用备选方案
    public Product hystrixGet(@PathVariable("id") Long id) {
        return new Product().setId(0).setImg("default").setPrice(0.00).setNum(0).setTitle("id ==>> " + id + ", 没有对应的信息.");
    }
}
